import { createRouter, createWebHistory } from 'vue-router';
import { authService } from '@/service/AuthService'; // 登录状态检查服务

const routes = [
  {
    path: '/Index',
    name: 'AgricultureDashboard',
    component: () => import('@/views/Index.vue'),
    meta: { requiresAuth: true },
  },

  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue'),
  },

  {
    path: '/',
    redirect: '/Index',
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

// 全局路由守卫
router.beforeEach((to, from, next) => {
  console.log("路由守卫 - requiresAuth:", to.meta.requiresAuth);
  console.log("路由守卫 - isLoggedIn:", authService.isLoggedIn);
  console.log("localStorage 中的 token:", localStorage.getItem("token")); // 检查 access_token
  if (to.meta.requiresAuth && !authService.isLoggedIn) {
    next({ name: 'login' });
  } else {
    next();
  }
});

export default router;